home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 2416 < prev    next >
Encoding:
Internet Message Format  |  1996-08-06  |  1.4 KB

  1. Path: locutus.rchland.ibm.com!usenet
  2. From: pstaite@vnet.ibm.com
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: problems w/ relational operator ==
  5. Date: 17 Jan 1996 15:14:56 GMT
  6. Organization: IBM OS/2 Device Driver Development  Rochester, MN
  7. Message-ID: <4dj3pg$ldl@locutus.rchland.ibm.com>
  8. References: <30FC83D2.7B6A@hti.net>
  9. Reply-To: pstaite@vnet.ibm.com
  10. NNTP-Posting-Host: warpone.rchland.ibm.com
  11. X-Newsreader: IBM NewsReader/2 v1.2
  12.  
  13. In <30FC83D2.7B6A@hti.net>, Michael Benrud <mbenrud@hti.net> writes:
  14. >I am having some problems using the == operator. I am using BC 4.02.
  15. >I have the following snipet of code:
  16. >
  17. >double i;
  18. >
  19. >if(i == 1.0)
  20. >  Xinc = Xinc * 10;
  21. >
  22. >The problem is that when i equals 1.0, the if statement never executes 
  23. >Xinc = Xinc * 10. Any ideas? Thanks in advance.
  24.  
  25. Are you sure, really really sure, that i is *exactly* 1.0???  Remember, 
  26. float and double are *approximations* and may not be exact.  How is i 
  27. calculated?  Try this:
  28.  
  29.   if( i == 1.0 )
  30.     Xinc *= 10;
  31.   else
  32.     cerr << "i not 1.0, diff is: " << ( i - 1.0 ) << endl;
  33.  
  34. If you get some unbelievably small number in exponential notation then 
  35. you know you have an inexact match.  You're probably calculating i or 
  36. incrementing it by some fraction that is not exactly representable. 
  37. Then you could try:
  38.  
  39. double maxerr = 0.00001;
  40.  
  41. if( fabs( i - 1.0 ) < maxerr )
  42.     Xinc *= 10;
  43.  
  44. or something like that...
  45.  
  46.  
  47. Phil Staite, team OS/2
  48. internet: pstaite@vnet.ibm.com  internal: pstaite@rchland
  49.  
  50.